#Boa:Frame:Peer

import wx
import driver,passenger
from common import *
import database
import registerDlg,ResponseDlg,RequestDlg,ServiceDlg
def create(parent):
    return Peer(parent)

[wxID_PEER, wxID_PEERACCEPT, wxID_PEERDRIVER, wxID_PEERLOGIN, 
 wxID_PEERMESSAGE, wxID_PEERPANEL1, wxID_PEERPASSENGER, wxID_PEERPHONE, 
 wxID_PEERPUBLISH, wxID_PEERREGIST, wxID_PEERREJECT, wxID_PEERSCROLLEDWINDOW1, 
 wxID_PEERSTATICTEXT1, 
] = [wx.NewId() for _init_ctrls in range(13)]

class TxtCtrlHandler(logging.Handler):
    def __init__(self,ctrl):
        logging.Handler.__init__(self)
        self.ctrl = ctrl

    def emit(self, record):
        try:
            if True:

                msg = self.format(record).splitlines()
                for line in msg:
                    self.ctrl.AppendText(line+"\n")
            else:
                self.ctrl.AppendText(self.format(record))

        except:
            self.handleError(record)
class DialogReporter(Reporter):

    def __init__(self,owner,requestName,errorFunc=None,okFunc=None,timeout=10,async=True):
        super(DialogReporter,self).__init__(None,None,timeout,async)
        self.dlg = ResponseDlg.responseDlg(owner,errorFunc,okFunc)
        self.dlg.request.Value = requestName
        self.errorFunc = errorFunc
        self.okFunc = okFunc
    def notify(self,retCode,retInfo,extraInfo=None):
        self.dlg.result.Value = "%d %s"%(retCode,retInfo)
        if (self.errorFunc and retCode>=300) or (self.okFunc and recCode<300):
            try:

                ret = self.dlg.ShowModal()

            finally:

                self.dlg.Destroy()


class Peer(wx.Frame):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_PEER, name=u'Peer', parent=prnt,
              pos=wx.Point(460, 122), size=wx.Size(626, 600),
              style=wx.DEFAULT_FRAME_STYLE, title=u'Peer')
        self.SetClientSize(wx.Size(608, 555))
        self.Show(False)
        self.Bind(wx.EVT_CLOSE, self.OnDriverClose)

        self.phone = wx.Choice(choices=[], id=wxID_PEERPHONE, name=u'phone',
              parent=self, pos=wx.Point(24, 112), size=wx.Size(232, 26),
              style=0)
        self.phone.SetToolTipString(u'phone')
        self.phone.SetSelection(0)
        self.phone.SetLabel(u'')
        self.phone.SetHelpText(u'')

        self.login = wx.Button(id=wxID_PEERLOGIN, label=u'login', name=u'login',
              parent=self, pos=wx.Point(280, 112), size=wx.Size(100, 31),
              style=0)
        self.login.Bind(wx.EVT_BUTTON, self.OnLoginButton, id=wxID_PEERLOGIN)

        self.panel1 = wx.Panel(id=wxID_PEERPANEL1, name='panel1', parent=self,
              pos=wx.Point(16, 168), size=wx.Size(576, 344),
              style=wx.TAB_TRAVERSAL)

        self.scrolledWindow1 = wx.ScrolledWindow(id=wxID_PEERSCROLLEDWINDOW1,
              name='scrolledWindow1', parent=self.panel1, pos=wx.Point(32, 32),
              size=wx.Size(520, 312), style=wx.HSCROLL | wx.VSCROLL)

        self.message = wx.TextCtrl(id=wxID_PEERMESSAGE, name=u'message',
              parent=self.scrolledWindow1, pos=wx.Point(8, 8), size=wx.Size(504,
              232), style=wx.TE_MULTILINE, value=u'')

        self.staticText1 = wx.StaticText(id=wxID_PEERSTATICTEXT1,
              label=u'request', name='staticText1', parent=self.panel1,
              pos=wx.Point(40, 8), size=wx.Size(49, 18), style=0)

        self.regist = wx.Button(id=wxID_PEERREGIST, label=u'regist',
              name=u'regist', parent=self, pos=wx.Point(280, 16),
              size=wx.Size(100, 31), style=0)
        self.regist.Bind(wx.EVT_BUTTON, self.OnRegistButton, id=wxID_PEERREGIST)

        self.driver = wx.RadioButton(id=wxID_PEERDRIVER, label=u'driver',
              name=u'driver', parent=self, pos=wx.Point(32, 16),
              size=wx.Size(108, 18), style=0)
        self.driver.SetValue(False)
        self.driver.Bind(wx.EVT_RADIOBUTTON, self.OnDriverRadiobutton,
              id=wxID_PEERDRIVER)

        self.passenger = wx.RadioButton(id=wxID_PEERPASSENGER,
              label=u'passenger', name=u'passenger', parent=self,
              pos=wx.Point(32, 64), size=wx.Size(108, 18), style=0)
        self.passenger.SetValue(True)
        self.passenger.Bind(wx.EVT_RADIOBUTTON, self.OnPassengerRadiobutton,
              id=wxID_PEERPASSENGER)

        self.publish = wx.Button(id=wxID_PEERPUBLISH, label=u'publish',
              name=u'publish', parent=self, pos=wx.Point(280, 64),
              size=wx.Size(100, 31), style=0)
        self.publish.Bind(wx.EVT_BUTTON, self.OnPublishButton,
              id=wxID_PEERPUBLISH)

        self.accept = wx.Button(id=wxID_PEERACCEPT, label=u'accept',
              name=u'accept', parent=self.scrolledWindow1, pos=wx.Point(96,
              272), size=wx.Size(100, 31), style=0)
        self.accept.Bind(wx.EVT_BUTTON, self.OnAcceptButton, id=wxID_PEERACCEPT)

        self.reject = wx.Button(id=wxID_PEERREJECT, label=u'reject',
              name=u'reject', parent=self.scrolledWindow1, pos=wx.Point(296,
              272), size=wx.Size(100, 31), style=0)
        self.reject.Bind(wx.EVT_BUTTON, self.OnRejectButton, id=wxID_PEERREJECT)

    def __init__(self, parent):
        self._init_ctrls(parent)
        """
        msgHandler = TxtCtrlHandler(self.message)
        formatter = logging.Formatter('%(asctime)s: %(levelname)s %(module)s.%(funcName)s-> %(message)s')
        msgHandler.setFormatter(formatter)
        self.log = logging.getLogger('')
        self.log.addHandler(msgHandler)
        """
        self.db = database.CreateDB()
        self.role = EPR_PASSENGER
        self._getUserList(self.role==EPR_DRIVER)
        self.publish.Hide()
        self.accept.Hide()
        self.reject.Hide()
        self.appendLog("begin")

    def appendLog(self,log):
        self.message.SetModified(True)
        self.message.ChangeValue("%s\n"%log)#AppendText

    def handleRequest(self,method,info,reporter):
        """
        dlg = RequestDlg.InfoDlg(self)
        dlg.appendInfo(method,info)
        ret = 0
        try:
            ret = dlg.ShowModal()
        finally:

            dlg.Destroy()
        return ret==wx.ID_OK
        """
        
        self.appendLog("%s\n%s\n"%(method,info))
        self.reporter = reporter
        self.accept.Show()
        self.reject.Show()

    def handleError(self,retCode,retInfo,extraInfo=None):
        pass

    def OnDriverClose(self, event):
        event.Skip()
        reporter = DialogReporter(self,"LOGOUT")
        try:
            self.peer.exit(reporter)
        except Exception,e:
            self.appendLog("logout fail\nreason: %s"%e)

    def _getUserList(self,isDriver):
        result = self.db.fetchall("driver",None)
        driverList=[]
        for row in result:
            driverList.append(row[-1])
        if not isDriver:
            result = self.db.fetchall("user",None)
            passengerList=[]
            for row in result:
                if not row[0] in driverList:
                    passengerList.append(row[0])
            self.phone.Items = passengerList
        else:
            self.phone.Items = driverList
        self.phone.Selection = 0

    def OnLoginButton(self, event):
        event.Skip()
        self.regist.Hide()
        try:
            if self.role==EPR_DRIVER:
                self.peer = driver.Driver(driverAddr,self)
            else:
                self.peer = passenger.Passenger(passengerAddr,self)
            phone = self.phone.Items[self.phone.Selection]
            reporter = DialogReporter(self,"LOGIN")
            self.peer.logIn(phone,"fdd",centerID,centerAddr,reporter)
            self.appendLog("login successfully")
            if self.role!=EPR_DRIVER:
                 self.publish.Show()
            self.login.Hide()
        except Exception,e:
            self.appendLog("login fail,please try again\nreason: %s"%e)

    def OnRegistButton(self, event):

        regist = registerDlg.register(self,self.role)#wx.ID_OK wx.ID_CANCEL
        try:
            ret = regist.ShowModal()
        finally:

            regist.Destroy()
        event.Skip()

    def OnDriverRadiobutton(self, event):
        self.role = EPR_DRIVER
        self._getUserList(True)
        event.Skip()

    def OnPassengerRadiobutton(self, event):
        self.role = EPR_PASSENGER
        self._getUserList(False)
        event.Skip()

    def Publish(self,departureLocation,departureTime,status,timeout,destinationLocation,destinationTime,price):
        try:
            self.peer.addService(None,departureLocation,departureTime,status,timeout,destinationLocation,destinationTime,price)
        except Exception,e:
            self.appendLog("publish fail\nreason: %s"%e)

    def OnPublishButton(self, event):
        event.Skip()
        dlg = ServiceDlg.serviceDlg(self)
        try:
            ret = dlg.ShowModal()
        finally:

            dlg.Destroy()

    def OnAcceptButton(self, event):
        event.Skip()
        self.accept.Hide()
        self.reject.Hide()
        self.reporter.notify(EN_OK,retCodeMap[EN_OK])

    def OnRejectButton(self, event):
        event.Skip()
        self.accept.Hide()
        self.reject.Hide()
        self.reporter.notify(EN_CANCEL,retCodeMap[EN_CANCEL])
